package cn.luowb.checkchat.service.impl;

import cn.luowb.checkchat.common.context.UserContext;
import cn.luowb.checkchat.dao.entity.MediaResourceDO;
import cn.luowb.checkchat.dao.entity.PostCollectionDO;
import cn.luowb.checkchat.dao.entity.PostDO;
import cn.luowb.checkchat.dao.mapper.PostCollectionMapper;
import cn.luowb.checkchat.dto.resp.CollectionItemVO;
import cn.luowb.checkchat.dto.resp.PostCollectionVO;
import cn.luowb.checkchat.service.MediaResourceService;
import cn.luowb.checkchat.service.PostCollectionService;
import cn.luowb.checkchat.service.PostService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author heimenkyou
 * @description 针对表【post_collection(收藏)】的数据库操作Service实现
 * @createDate 2025-09-01 19:07:09
 */
@Service
public class PostCollectionServiceImpl extends ServiceImpl<PostCollectionMapper, PostCollectionDO>
        implements PostCollectionService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PostService postService;

    private final static String key="check-chat:collection:";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MediaResourceService mediaResourceService;

    @Override
    public boolean toggle(Long postId) {
        //1.获取用户id
        Long userId= UserContext.getUserId();
        //Long userId=1L;
        //2.判断用户是否收藏
        Boolean  existed= stringRedisTemplate.opsForSet().isMember(key + postId, userId.toString());
        //3.没收藏，添加
        if(!existed){
                //修改数据库+1
            postService.update().eq("id", postId).setSql("collection_count=collection_count+1").update();
            PostCollectionDO postCollectionDO = new PostCollectionDO();
            postCollectionDO.setUid(userId);
            postCollectionDO.setPostId(postId);
//            System.out.println("即将插入的对象：" + postCollectionDO.getPostId());
            save(postCollectionDO);

            //添加redis
            stringRedisTemplate.opsForSet().add(key + postId, userId.toString());
        }
        //4，收藏，删除
        else {
            //修改数据库-1
            postService.update().eq("id", postId).setSql("collection_count=collection_count-1").update();
            //删除数据库
            PostCollectionDO postCollection = lambdaQuery()
                    .eq(PostCollectionDO::getUid, userId)
                    .eq(PostCollectionDO::getPostId, postId)
                    .one();
        if (postCollection != null) {
            removeById(postCollection.getId());
        }
            //删除redis
            stringRedisTemplate.opsForSet().remove(key + postId, userId.toString());
        }
        // 返回最终的收藏状态
        return !existed;
    }

    @Override
    public PostCollectionVO getList(Integer size, Long lastId) {
        //获取用户id
        Long userId= UserContext.getUserId();
       //Long userId=1L;
        //查询收藏的帖子id
        List<PostCollectionDO> collectionList = query().eq("uid", userId).list();
//        for(PostCollectionDO postCollectionDO : collectionList){
//            System.out.println("收藏的帖子id：" + postCollectionDO.getPostId());
//        }


        // 提取帖子ID列表（从PostCollectionDO对象中提取postId）
        List<Long> postIds = collectionList.stream()
                .map(PostCollectionDO::getPostId)
                .collect(java.util.stream.Collectors.toList());
        //为空直接返回
        if(postIds.isEmpty()){
            PostCollectionVO res=new PostCollectionVO();
            res.setPosts(new ArrayList<>());
            res.setSize(0);
            res.setLastId(1L);
            return res;
        }
        if(lastId==0){
            lastId=Long.MAX_VALUE;
        }
        //查询数据库中左右的收藏帖子，按时间排列
        LambdaQueryWrapper<PostDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PostDO::getId, postIds)
                .orderByDesc(PostDO::getCreateTime)
                .lt(PostDO::getId, lastId)
                .last("LIMIT "+ size);
        List<PostDO> postList = postService.list(queryWrapper);
        for(PostDO postDO : postList){
            System.out.println("查询到的对象：" + postDO.getId());
        }
        List<CollectionItemVO> collectionItemVOList = new ArrayList<>();
        for (PostDO postDO : postList) {
            CollectionItemVO collectionItemVO = new CollectionItemVO();
            collectionItemVO.setId(postDO.getId());
            collectionItemVO.setUid(postDO.getUid());
            collectionItemVO.setCateId(postDO.getCateId());
            collectionItemVO.setTitle(postDO.getTitle());
            collectionItemVO.setContent(postDO.getContent());
            //查询媒体资源
            List<MediaResourceDO> mediaList=mediaResourceService.query().eq("ref_id", postDO.getId()).list();
            List<String> urlList=mediaList.stream().map(MediaResourceDO::getUrl).toList();
            collectionItemVO.setMedia(urlList);
            collectionItemVO.setReadCount(postDO.getReadCount());
            collectionItemVO.setLikeCount(postDO.getLikeCount());
            collectionItemVO.setCreateTime(postDO.getCreateTime());
//            System.out.println("转换后的对象：" + collectionItemVO.getId());
            collectionItemVOList.add(collectionItemVO);
        }

        //计算minTime
        LocalDateTime minTime=null;
        if(!postList.isEmpty()){
            lastId=collectionItemVOList.get(collectionItemVOList.size()-1).getId();
        }



        //组装返回值
        PostCollectionVO res=new PostCollectionVO();
        res.setPosts(collectionItemVOList);
        res.setSize(size);
        res.setLastId(lastId);
        return res;
    }
}




